<template>
  <BasicDrawer v-bind="$attrs" :title="getTitle" width="50%" @register="register">
    <div>
      <BasicForm @register="registerForm" />
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { computed, ref } from 'vue';

  import { createUser, updateUser } from '@/api/page/user_audit';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { useMessage } from '@/hooks/web/useMessage';

  import { detailSchemas } from './data';

  const { createMessage } = useMessage();
  const emit = defineEmits(['next', 'register']);
  const getTitle = computed(() => title.value);
  const title = ref<string>('');
  const details = ref<object>({});

  const [registerForm, { setFieldsValue, validate, resetFields, setProps }] = useForm({
    labelWidth: 120,
    schemas: detailSchemas(),
    // layout: 'vertical',
    actionColOptions: {
      span: 24,
    },
    // showActionButtonGroup: false,
    showResetButton: false,
    showSubmitButton: true,
    submitButtonOptions: {
      text: '提交',
    },
    submitFunc: customSubmitFunc,
  });

  function getDetailSchemas(schemas, bool) {
    const schemasDetail = schemas.map((item) => ({
      ...item,
      componentProps: {
        ...item.componentProps,
        disabled: item.field != 'username' && item.field != 'role' ? bool : title.value === '添加' ? false : true,
      },
      ifShow: item.field === 'password' ? (title.value === '添加'? true : false) : true,
    }));
    return schemasDetail;
  }
  const [register] = useDrawerInner((data) => {
    resetFields();
    title.value = data.title;
    details.value = data.record || {};
    if (data.title === '详情') {
      const schemasDetail = getDetailSchemas(detailSchemas(), true);
      setProps({
        showSubmitButton: false,
        schemas: schemasDetail,
      });
    } else {
      const schemasDetail = getDetailSchemas(detailSchemas(), false);
      setProps({
        showSubmitButton: true,
        schemas: schemasDetail,
      });
    }

    data.record &&
      setFieldsValue({
        ...data.record,
      });
  });

  async function customSubmitFunc() {
    try {
      const values = await validate();
      if (title.value === '添加') {
        createUser(values).then((res) => {
          if (res.code === 1000) {
            createMessage.success('添加成功！');
            emit('next', values);
          } else {
            createMessage.error(res.msg);
          }
        });
      } else {
        const params = Object.assign({}, details.value, values);
        updateUser(params).then((res) => {
          if (res.code === 1000) {
            createMessage.success('修改成功！');
            emit('next', values);
          } else {
            createMessage.error(res.msg);
          }
        });
      }
    } catch (error) {
      //
    }
  }
</script>
